/*
 * JFrPlayersQuickCheck.java
 */

package gotha;

import java.rmi.*;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.*;

/**
 *
 * @author  Administrateur
 */
public class JFrPlayersQuickCheck extends javax.swing.JFrame{
    private static final long REFRESH_DELAY = 2000;
    private long lastComponentsUpdateTime = 0;

    
    private static final int PLAYER_NUMBER_COL = 0;
    public  static final int REG_COL = 1;
    private static final int NAME_COL = 2;
    private static final int FIRSTNAME_COL = 3;
    private static final int RANK_COL = 4;
    private static final int COUNTRY_COL = 5;
    private static final int CLUB_COL = 6;
    
    private int playersSortType = PlayerComparator.NAME_ORDER;
    private ArrayList<Player> alSelectedPlayersToKeepSelected = new ArrayList<Player>(); 

    private TournamentInterface tournament;
    /**
     * Creates new form JFrPlayersQuickCheck
     */
    public JFrPlayersQuickCheck() {
        initComponents();
        setupRefreshTimer();
    }

    private void setupRefreshTimer(){
        ActionListener taskPerformer = new ActionListener(){
            public void actionPerformed(ActionEvent evt){
                try {
                    if (tournament.getLastTournamentModificationTime() > lastComponentsUpdateTime) {
                        updateAllViews();
                    }
                } catch (RemoteException ex) {
                    Logger.getLogger(JFrGamesResults.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        };
        new javax.swing.Timer((int) REFRESH_DELAY, taskPerformer).start();
    }
    public JFrPlayersQuickCheck(TournamentInterface tournament) throws RemoteException{
        this.tournament = tournament;
        
        initComponents();
        customInitComponents();
        setupRefreshTimer();
    }    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pupRegisteredPlayers = new javax.swing.JPopupMenu();
        mniSortByName = new javax.swing.JMenuItem();
        mniSortByRank = new javax.swing.JMenuItem();
        pnlInternal = new javax.swing.JPanel();
        btnQuit = new javax.swing.JButton();
        pnlPlayersList = new javax.swing.JPanel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        txfNbPlFin = new javax.swing.JTextField();
        txfNbPlPre = new javax.swing.JTextField();
        scpRegisteredPlayers = new javax.swing.JScrollPane();
        tblRegisteredPlayers = new javax.swing.JTable();
        btnPrint = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        btnRemovePrePlayers = new javax.swing.JButton();
        btnIncreaseRank = new javax.swing.JButton();
        btnDecreaseRank = new javax.swing.JButton();
        btnSetRegToFin = new javax.swing.JButton();
        btnSetRegToPre = new javax.swing.JButton();
        btnHelp = new javax.swing.JButton();

        pupRegisteredPlayers.setFont(new java.awt.Font("Arial", 0, 11));
        pupRegisteredPlayers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseExited(java.awt.event.MouseEvent evt) {
                pupRegisteredPlayersMouseExited(evt);
            }
        });

        mniSortByName.setFont(new java.awt.Font("Arial", 0, 11));
        mniSortByName.setText("Sort by name");
        mniSortByName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniSortByNameActionPerformed(evt);
            }
        });
        pupRegisteredPlayers.add(mniSortByName);

        mniSortByRank.setFont(new java.awt.Font("Arial", 0, 11));
        mniSortByRank.setText("Sort by rank");
        mniSortByRank.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mniSortByRankActionPerformed(evt);
            }
        });
        pupRegisteredPlayers.add(mniSortByRank);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Players Quick check");
        setResizable(false);
        getContentPane().setLayout(null);

        pnlInternal.setLayout(null);

        btnQuit.setText("Quit");
        btnQuit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitActionPerformed(evt);
            }
        });
        pnlInternal.add(btnQuit);
        btnQuit.setBounds(190, 470, 200, 30);

        pnlPlayersList.setBorder(javax.swing.BorderFactory.createTitledBorder("List of players"));
        pnlPlayersList.setLayout(null);

        jLabel8.setText("Registered players. Final (F)");
        pnlPlayersList.add(jLabel8);
        jLabel8.setBounds(60, 50, 250, 20);

        jLabel9.setText("Registered players. Preliminary (P)");
        pnlPlayersList.add(jLabel9);
        jLabel9.setBounds(60, 30, 250, 20);

        txfNbPlFin.setEditable(false);
        txfNbPlFin.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txfNbPlFin.setEnabled(false);
        pnlPlayersList.add(txfNbPlFin);
        txfNbPlFin.setBounds(10, 50, 40, 20);

        txfNbPlPre.setEditable(false);
        txfNbPlPre.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txfNbPlPre.setEnabled(false);
        pnlPlayersList.add(txfNbPlPre);
        txfNbPlPre.setBounds(10, 30, 40, 20);

        scpRegisteredPlayers.setToolTipText("");

        tblRegisteredPlayers.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "Number", "R", "Name", "First name", "Rk", "Co", "Club"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblRegisteredPlayers.setToolTipText("To modify, right click !");
        tblRegisteredPlayers.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tblRegisteredPlayersKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                tblRegisteredPlayersKeyTyped(evt);
            }
        });
        tblRegisteredPlayers.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblRegisteredPlayersMouseClicked(evt);
            }
        });
        scpRegisteredPlayers.setViewportView(tblRegisteredPlayers);

        pnlPlayersList.add(scpRegisteredPlayers);
        scpRegisteredPlayers.setBounds(10, 80, 300, 330);

        btnPrint.setText("Print ...");
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        pnlPlayersList.add(btnPrint);
        btnPrint.setBounds(10, 420, 300, 30);

        pnlInternal.add(pnlPlayersList);
        pnlPlayersList.setBounds(70, 10, 320, 460);

        jLabel1.setText("Action on selected players");
        pnlInternal.add(jLabel1);
        jLabel1.setBounds(430, 100, 220, 14);

        jLabel6.setFont(new java.awt.Font("Arial", 0, 24));
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel6.setText("+");
        jLabel6.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pnlInternal.add(jLabel6);
        jLabel6.setBounds(430, 120, 20, 30);

        jLabel10.setFont(new java.awt.Font("Arial", 0, 24));
        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel10.setText("-");
        jLabel10.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pnlInternal.add(jLabel10);
        jLabel10.setBounds(430, 160, 20, 30);

        jLabel13.setFont(new java.awt.Font("Arial", 0, 18));
        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel13.setText("F");
        jLabel13.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pnlInternal.add(jLabel13);
        jLabel13.setBounds(430, 200, 20, 20);

        jLabel16.setFont(new java.awt.Font("Arial", 0, 18));
        jLabel16.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel16.setText("P");
        jLabel16.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        pnlInternal.add(jLabel16);
        jLabel16.setBounds(430, 240, 20, 20);

        btnRemovePrePlayers.setText("Remove all \"P\" players");
        btnRemovePrePlayers.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemovePrePlayersActionPerformed(evt);
            }
        });
        pnlInternal.add(btnRemovePrePlayers);
        btnRemovePrePlayers.setBounds(430, 300, 280, 30);

        btnIncreaseRank.setText("Increase rank of selected players");
        btnIncreaseRank.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncreaseRankActionPerformed(evt);
            }
        });
        pnlInternal.add(btnIncreaseRank);
        btnIncreaseRank.setBounds(460, 120, 250, 30);

        btnDecreaseRank.setText("Decrease rank of selected players");
        btnDecreaseRank.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDecreaseRankActionPerformed(evt);
            }
        });
        pnlInternal.add(btnDecreaseRank);
        btnDecreaseRank.setBounds(460, 160, 250, 30);

        btnSetRegToFin.setText("Set Registration status to Final");
        btnSetRegToFin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSetRegToFinActionPerformed(evt);
            }
        });
        pnlInternal.add(btnSetRegToFin);
        btnSetRegToFin.setBounds(460, 200, 250, 30);

        btnSetRegToPre.setText("Set Registration status to Preliminary");
        btnSetRegToPre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSetRegToPreActionPerformed(evt);
            }
        });
        pnlInternal.add(btnSetRegToPre);
        btnSetRegToPre.setBounds(460, 240, 250, 30);

        btnHelp.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gotha/gothalogo16.jpg"))); // NOI18N
        btnHelp.setText("help");
        btnHelp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnHelpActionPerformed(evt);
            }
        });
        pnlInternal.add(btnHelp);
        btnHelp.setBounds(70, 470, 110, 30);

        getContentPane().add(pnlInternal);
        pnlInternal.setBounds(0, 0, 790, 510);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSetRegToFinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSetRegToFinActionPerformed
        ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
        // Keep a track of selected Players
        alSelectedPlayersToKeepSelected = new ArrayList<Player>(alP);
        
        if (alP.size() == 0) {
            JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        this.setPlayersRegStatus(alP, 'F');
    }//GEN-LAST:event_btnSetRegToFinActionPerformed

    private void btnSetRegToPreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSetRegToPreActionPerformed
        ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
        // Keep a track of selected Players
        alSelectedPlayersToKeepSelected = new ArrayList<Player>(alP);
        
        if (alP.size() == 0) {
            JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        this.setPlayersRegStatus(alP, 'P');
    }//GEN-LAST:event_btnSetRegToPreActionPerformed

    private void btnDecreaseRankActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDecreaseRankActionPerformed
        ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
        // Keep a track of selected Players
        alSelectedPlayersToKeepSelected = new ArrayList<Player>(alP);
        
        if (alP.size() == 0) {
            JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        this.changePlayersRank(alP, -1);
    }//GEN-LAST:event_btnDecreaseRankActionPerformed

    private void btnIncreaseRankActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncreaseRankActionPerformed
        ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
        // Keep a track of selected Players
        alSelectedPlayersToKeepSelected = new ArrayList<Player>(alP);
        
        if (alP.size() == 0) {
            JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        this.changePlayersRank(alP, 1);
    }//GEN-LAST:event_btnIncreaseRankActionPerformed

    private void pupRegisteredPlayersMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_pupRegisteredPlayersMouseExited
        pupRegisteredPlayers.setVisible(false);
    }//GEN-LAST:event_pupRegisteredPlayersMouseExited

    private void btnRemovePrePlayersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemovePrePlayersActionPerformed
        ArrayList<Player> alP = null;
        try {
            alP = tournament.playersList();
        } catch (RemoteException ex) {
            ex.printStackTrace();
            return;
        }
        int nbP = 0;
        for (Player p: alP){
            if (p.getRegisteringStatus().compareTo("PRE") == 0) nbP++;
        }
        if (nbP == 0) {
            JOptionPane.showMessageDialog(this, "No player is in a preliminary status", "Message", JOptionPane.ERROR_MESSAGE);
            return;
        }
        int response =  JOptionPane.showConfirmDialog(this, "" + nbP + " " + "players will be removed", "Message", JOptionPane.OK_CANCEL_OPTION);
        if (response == JOptionPane.OK_OPTION){
            int nbRemovedPlayers = 0;
            int nbNotRemovedPlayers = 0;
            for (Player p: alP){
                if (p.getRegisteringStatus().compareTo("PRE") == 0){
                    try {
                        tournament.removePlayer(p);
                        nbRemovedPlayers++;
                    } catch (RemoteException ex) {
                        ex.printStackTrace();
                    } catch (TournamentException ex) {
                        nbNotRemovedPlayers++;
                        ex.printStackTrace();
                    }
                }
            }
            
            if (nbNotRemovedPlayers != 0){
                String strMessage = "";
                if (nbNotRemovedPlayers == 1) strMessage = "player could not be removed";
                else strMessage = "players could not be removed";
                        JOptionPane.showMessageDialog(this, "" + nbNotRemovedPlayers + strMessage,
                        "Message", JOptionPane.WARNING_MESSAGE);
            }
            if (nbRemovedPlayers > 0){
                this.tournamentChanged();
            }

        }
        
    }//GEN-LAST:event_btnRemovePrePlayersActionPerformed

    private void mniSortByRankActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniSortByRankActionPerformed
        playersSortType = PlayerComparator.RANK_ORDER;
        pupRegisteredPlayers.setVisible(false);
        try{
            updatePnlRegisteredPlayers(tournament.playersList());
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_mniSortByRankActionPerformed

    private void mniSortByNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mniSortByNameActionPerformed
        playersSortType = PlayerComparator.NAME_ORDER;
        pupRegisteredPlayers.setVisible(false);
        try{
            updatePnlRegisteredPlayers(tournament.playersList());
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_mniSortByNameActionPerformed

    private void tblRegisteredPlayersKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblRegisteredPlayersKeyTyped
        ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
        // Keep a track of selected Players
        alSelectedPlayersToKeepSelected = new ArrayList<Player>(alP);

        if (alP.size() == 0) {
            JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                    JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (evt.getKeyChar() == '+') this.changePlayersRank(alP, 1);
        else if (evt.getKeyChar() == '-') this.changePlayersRank(alP, -1);
        else if (evt.getKeyChar() == 'P' || evt.getKeyChar() == 'p') this.setPlayersRegStatus(alP, 'P');
        else if (evt.getKeyChar() == 'F' || evt.getKeyChar() == 'f') this.setPlayersRegStatus(alP, 'F');

    }//GEN-LAST:event_tblRegisteredPlayersKeyTyped

    /** changes rank of players in alP by deltaRank
     */
    private void changePlayersRank(ArrayList<Player> alP, int deltaRank){
        boolean bSomethingHasChanged = false;
        int confirm = JOptionPane.OK_OPTION;                
        if (alP.size() > 1) confirm = JOptionPane.showConfirmDialog(this, "Rank will be modified for " + alP.size() + " players", 
                "Message", JOptionPane.OK_CANCEL_OPTION);
        if (confirm == JOptionPane.OK_OPTION){
            try {
                for (Player p : alP){
                     p.setRank(p.getRank() + deltaRank);
                     tournament.modifyPlayer(p, p);
                }
            } catch (RemoteException ex) {
                ex.printStackTrace();
            } catch (TournamentException ex) {
                ex.printStackTrace();
            }
            bSomethingHasChanged = true;  
        }
        
        if (bSomethingHasChanged){
            this.tournamentChanged();
        }
    }

    /** sets registration status of alP to newRegStatus
     */
    private void setPlayersRegStatus(ArrayList<Player> alP, char newRegStatus){
        boolean bSomethingHasChanged = false;
        if (newRegStatus == 'P'){
            int nbPlayersMod = 0;
            int nbPlayersPRE = 0;
            for (Player p : alP){
                if (p.getRegisteringStatus().compareTo("PRE") == 0) nbPlayersPRE++;
                else{
                    try {
                        if (!tournament.isPlayerImplied(p)){
                            p.setRegisteringStatus("PRE");
                            tournament.modifyPlayer(p, p);
                            nbPlayersMod++;
                        }
                    } catch (RemoteException ex) {
                        ex.printStackTrace();
                    } catch (TournamentException ex) {
                        ex.printStackTrace();
                    }
                }
            }
            int nbPlayersNotModifiable = alP.size() - nbPlayersPRE - nbPlayersMod;
            if (nbPlayersNotModifiable >= 1){
                String strMessage = "";
                if (nbPlayersNotModifiable == 1) strMessage = "player could not be changed because already assigned";
                else strMessage = "players could not be changed because already assigned";
                strMessage = "" + nbPlayersNotModifiable + " " + strMessage;
                JOptionPane.showMessageDialog(this, strMessage, "Message", JOptionPane.WARNING_MESSAGE);
            }
            if (nbPlayersMod != 0) bSomethingHasChanged = true;
        }
        if (newRegStatus == 'F'){
            int nbPlayersMod = 0;
            for (Player p : alP){
                if (p.getRegisteringStatus().compareTo("FIN") != 0){
                    p.setRegisteringStatus("FIN");
                    try {
                        tournament.modifyPlayer(p, p);
                    } catch (RemoteException ex) {
                        ex.printStackTrace();
                    } catch (TournamentException ex) {
                        ex.printStackTrace();
                    }
                    nbPlayersMod++;
                }
            }
            if (nbPlayersMod != 0) bSomethingHasChanged = true;
        }
        if (bSomethingHasChanged){
            this.tournamentChanged();
        }
    }

    
    
    private void btnQuitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitActionPerformed
        dispose();
    }//GEN-LAST:event_btnQuitActionPerformed

    private void tblRegisteredPlayersKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tblRegisteredPlayersKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_DELETE){
            ArrayList<Player> alP = this.selectedPlayersList(this.tblRegisteredPlayers);
            if (alP.size() == 0) {
                JOptionPane.showMessageDialog(this, "Please, select at least one player", "Message",
                        JOptionPane.ERROR_MESSAGE); 
                return;
            }
 
            int nbJ = alP.size();
            String strMessage = "";
            if (nbJ == 1) strMessage = "player will be removed";
            else strMessage = "players will be removed";
            if (JOptionPane.showConfirmDialog(this, "" + nbJ + " " + strMessage, "Message",
                    JOptionPane.OK_CANCEL_OPTION) != JOptionPane.OK_OPTION) return;
            int nbPlayersRem = removePlayers(alP);
            int nbPlayersNotRem = alP.size() - nbPlayersRem;
            
            strMessage = "";
            int messageType = JOptionPane.INFORMATION_MESSAGE;
            if (nbPlayersNotRem >= 1){
                if (nbPlayersNotRem <= 1) strMessage = "player could not be removed";
                else strMessage = "players could not be removed";
                strMessage = nbPlayersNotRem + strMessage + "\n";
                messageType = JOptionPane.WARNING_MESSAGE;
            }
            if (nbPlayersRem == 1) strMessage += nbPlayersRem + " " + "player_has_been_removed";
            else strMessage += nbPlayersRem + " " + "players_have_been_removed";
            JOptionPane.showMessageDialog(this, strMessage, "Message", messageType);
            if (nbPlayersRem > 0){
                this.tournamentChanged();
            }
        }
    }//GEN-LAST:event_tblRegisteredPlayersKeyPressed

    private void tblRegisteredPlayersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblRegisteredPlayersMouseClicked
        // Double or multiple click
        // Right click
        if (evt.getModifiers() == InputEvent.BUTTON3_MASK){
            int x1 = this.getX();
            int x2 = this.pnlInternal.getX();
            int x3 = this.pnlPlayersList.getX();
            int x4 = this.scpRegisteredPlayers.getX();
            int x5 = this.tblRegisteredPlayers.getX();
            int x = x1 + x2 + x3 + x4 + x5 + evt.getX();
            
            int y1 = this.getY();
            int y2 = this.pnlInternal.getY();
            int y3 = this.pnlPlayersList.getY();
            int y4 = this.scpRegisteredPlayers.getY();
            int y5 = this.tblRegisteredPlayers.getY();
            int y = y1 + y2 + y3 + y4 + y5 + evt.getY() + 20;
        
            pupRegisteredPlayers.setLocation(x, y);
            this.pupRegisteredPlayers.setVisible(true);
        }
    }//GEN-LAST:event_tblRegisteredPlayersMouseClicked

    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
        TournamentPrinting tpr = new TournamentPrinting(tournament);
        tpr.setRoundNumber(-1);
        tpr.makePrinting(TournamentPrinting.TYPE_PLAYERSLIST, this.playersSortType);
    }//GEN-LAST:event_btnPrintActionPerformed

    private void btnHelpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnHelpActionPerformed
        Gotha.displayGothaHelp("Players Quick check frame");
}//GEN-LAST:event_btnHelpActionPerformed

    private void customInitComponents()throws RemoteException{       
        int w = JFrGotha.MEDIUM_FRAME_WIDTH;
        int h = JFrGotha.MEDIUM_FRAME_HEIGHT;
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((dim.width - w)/2, (dim.height -h)/2, w, h);
        
        // Column names in 
        TableColumnModel tcm = this.tblRegisteredPlayers.getColumnModel();
        tcm.getColumn(0).setHeaderValue("Number");
        tcm.getColumn(1).setHeaderValue("R");
        tcm.getColumn(2).setHeaderValue("Name");
        tcm.getColumn(3).setHeaderValue("First_name");
        tcm.getColumn(4).setHeaderValue("Rk");
        tcm.getColumn(5).setHeaderValue("Co");
        tcm.getColumn(6).setHeaderValue("Club");
        
        setIconImage(Gotha.getIconImage());
        initPnlRegisteredPlayers();
        updateComponents();
    }
    
    private void initPnlRegisteredPlayers()throws RemoteException{
        tblRegisteredPlayers.getColumnModel().getColumn(PLAYER_NUMBER_COL).setMinWidth(0);
        tblRegisteredPlayers.getColumnModel().getColumn(PLAYER_NUMBER_COL).setPreferredWidth(0);
        tblRegisteredPlayers.getColumnModel().getColumn(REG_COL).setPreferredWidth(10);
        tblRegisteredPlayers.getColumnModel().getColumn(NAME_COL).setPreferredWidth(110);
        tblRegisteredPlayers.getColumnModel().getColumn(FIRSTNAME_COL).setPreferredWidth(80);
        tblRegisteredPlayers.getColumnModel().getColumn(RANK_COL).setPreferredWidth(30);
        tblRegisteredPlayers.getColumnModel().getColumn(COUNTRY_COL).setPreferredWidth(30);
        tblRegisteredPlayers.getColumnModel().getColumn(CLUB_COL).setPreferredWidth(40);
        
        // Left alignment for headers
        ((DefaultTableCellRenderer)tblRegisteredPlayers.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.LEFT);
        
    }
    
    public void tournamentChanged(){
        try {
            if (!tournament.isOpen()){
                dispose();
                return;
            }
            tournament.setLastTournamentModificationTime(tournament.getCurrentTournamentTime());
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }

        updateAllViews();
    }

    private void updateAllViews(){
        try {
            this.lastComponentsUpdateTime = tournament.getCurrentTournamentTime();
            setTitle("Players Quick check. " + tournament.getTournamentParameterSet().getGeneralParameterSet().getShortName());        } catch (RemoteException ex) {
            Logger.getLogger(JFrPlayersQuickCheck.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        this.pnlInternal.setVisible(true);

        updateComponents();
        
    }        

    private void updateComponents(){
        ArrayList<Player> playersList = null;
        try {
            playersList = tournament.playersList();
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
        updatePnlRegisteredPlayers(playersList);
    }
    private void updatePnlRegisteredPlayers(ArrayList<Player> playersList){
        try {
            if (!tournament.isOpen()){
                this.pnlPlayersList.setVisible(false);
                return;
            }
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
        
        this.pnlPlayersList.setVisible(true);

        int nbPreliminary = 0;
        int nbFinal = 0;
        for (Player p : playersList){
            if (p.getRegisteringStatus().compareTo("PRE") == 0) nbPreliminary++;
            if (p.getRegisteringStatus().compareTo("FIN") == 0) nbFinal++;
        }
        txfNbPlPre.setText(""+ nbPreliminary);
        txfNbPlFin.setText(""+ nbFinal);
        
        DefaultTableModel model = (DefaultTableModel)tblRegisteredPlayers.getModel();

        
        ArrayList<Player> displayedPlayersList = new ArrayList<Player>(playersList);
        
        PlayerComparator playerComparator = new PlayerComparator(playersSortType);
        Collections.sort(displayedPlayersList, playerComparator);

        model.setRowCount(displayedPlayersList.size());
        for (Player p:displayedPlayersList){
            int iP = -1;
            int line = displayedPlayersList.indexOf(p); 
            model.setValueAt("" + iP, line, JFrPlayersQuickCheck.PLAYER_NUMBER_COL);
            model.setValueAt((p.getRegisteringStatus().compareTo("PRE")==0)?"P":"F", line, JFrPlayersQuickCheck.REG_COL);
            model.setValueAt(p.getName(), line, JFrPlayersQuickCheck.NAME_COL);
            model.setValueAt(p.getFirstName(), line, JFrPlayersQuickCheck.FIRSTNAME_COL);
            model.setValueAt(Player.convertIntToKD(p.getRank()), line, JFrPlayersQuickCheck.RANK_COL);
            model.setValueAt(p.getCountry(), line, JFrPlayersQuickCheck.COUNTRY_COL);
            model.setValueAt(p.getClub(), line, JFrPlayersQuickCheck.CLUB_COL);           
        }
        
        for (int nCol = 0; nCol < this.tblRegisteredPlayers.getColumnCount(); nCol++){
            TableColumn col = tblRegisteredPlayers.getColumnModel().getColumn(nCol);
            col.setCellRenderer(new PlayersQCTableCellRenderer());
        }
        
        // Reselect players that may have been deselected by this update
        for (Player p:alSelectedPlayersToKeepSelected){
            int iSel = displayedPlayersList.indexOf(p);
            if ( iSel >= 0) tblRegisteredPlayers.addRowSelectionInterval(iSel, iSel);
        }

    }
    
    private ArrayList<Player> selectedPlayersList(JTable tbl){
        ArrayList<Player> alSelectedPlayers = new ArrayList<Player>();
       
        // gather selected players into alSelectedPlayers
        for ( int iRow = 0; iRow < tbl.getModel().getRowCount(); iRow++){
            if (tbl.isRowSelected(iRow)){
                String name = (String)tbl.getModel().getValueAt(iRow, NAME_COL);
                String firstName = (String)tbl.getModel().getValueAt(iRow, FIRSTNAME_COL);
                Player p = null;
                try {
                    p = tournament.getPlayerByKeyString(name + firstName);
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                }
                alSelectedPlayers.add(p);
            }
        }
        return alSelectedPlayers;
    }
       
    private int removePlayers(ArrayList<Player> alP){
        int nbPlayersRem = 0;
        for (Player p : alP){
            boolean b = false;
            try {
                b = tournament.isPlayerImplied(p);
            } catch (RemoteException ex) {
                ex.printStackTrace();
            }
            if (!b){
                try{
                    Player playerToRemove = tournament.getPlayerByKeyString(p.getName() + p.getFirstName());
                    if(tournament.removePlayer(playerToRemove)) nbPlayersRem++;
                } catch(TournamentException te){
                    JOptionPane.showMessageDialog(this, te.getMessage(), "Message", JOptionPane.ERROR_MESSAGE);
                } catch (RemoteException ex) {
                    ex.printStackTrace();
                }
            }
        }
                
        return nbPlayersRem;
    }
       
  
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDecreaseRank;
    private javax.swing.JButton btnHelp;
    private javax.swing.JButton btnIncreaseRank;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnQuit;
    private javax.swing.JButton btnRemovePrePlayers;
    private javax.swing.JButton btnSetRegToFin;
    private javax.swing.JButton btnSetRegToPre;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JMenuItem mniSortByName;
    private javax.swing.JMenuItem mniSortByRank;
    private javax.swing.JPanel pnlInternal;
    private javax.swing.JPanel pnlPlayersList;
    private javax.swing.JPopupMenu pupRegisteredPlayers;
    private javax.swing.JScrollPane scpRegisteredPlayers;
    private javax.swing.JTable tblRegisteredPlayers;
    private javax.swing.JTextField txfNbPlFin;
    private javax.swing.JTextField txfNbPlPre;
    // End of variables declaration//GEN-END:variables
}

class PlayersQCTableCellRenderer extends JLabel implements TableCellRenderer {
    // This method is called each time a cell in a column
    // using this renderer needs to be rendered.
    public Component getTableCellRendererComponent(JTable table, Object value,
        boolean isSelected, boolean hasFocus, int rowIndex, int colIndex) {
        Component comp = new DefaultTableCellRenderer().getTableCellRendererComponent(table,  value, isSelected, hasFocus, rowIndex, colIndex);
        TableModel model = table.getModel();
        String strRegStatus = "" + model.getValueAt(rowIndex, JFrPlayersQuickCheck.REG_COL);

        if (strRegStatus.compareTo("P") == 0) comp.setForeground(Color.RED);
        else comp.setForeground(Color.BLACK);

        return comp;
    }
}
